import React,{Component} from 'react';
import {Form, Table, Button, Divider, Input, message, Popconfirm, Modal} from 'antd'
import AddOrUpdate from './add-or-update'
import { connect } from 'react-redux'
import { getDataList } from '../../../redux/actions/dict'
import dictColnumns from './dict-columns'

import { reqDeleteDict, reqUpdateDict, reqAddDict} from "../../../api/dict";
import './dict.less'

class Dict extends Component{
    state = {
        dataForm:{
            id: '',
            type: '',
            typeName: ''
        },
        visible: false,
        updateId: 0,
        totalCount: 0,
        currentPage: 1,
        pageSize: 10,
        dataList: [],
        listLoading: false
    }
    initColumns = () => {
        this.columns = [].concat(dictColnumns)
        this.columns.push({
            title: '操作',
            dataIndex: '',
            width: '180px',
            align: 'center',
            key: '8',
            render: (record) => {
                return(
                    <span>
                    <Button type="primary" size="small" onClick={() => this.handleAddOrUpdate(record._id)}>修改</Button>
                    <Divider type="vertical" />
                    <Popconfirm title="确定删除?" okText="确认" cancelText="取消" onConfirm={() => this.handleDelete(record.id)}>
                      <Button type="danger" size="small">删除</Button>
                    </Popconfirm>
                </span>
                )
            }
        })
    }
    getDataList = () => {
        this.setState({listLoading: true})
        let queryData = {
            page: this.state.currentPage,
            limit: this.state.pageSize
        }
        queryData = Object.assign(queryData, this.state.dataForm)

        let promise = this.props.getDataList(queryData)
        Promise.resolve(promise.data).then(({ data })=>{
           if(data && data.code === 0){
               this.setState({
                   dataList: data.dictList,
                   totalCount: data.totalCount,
                   listLoading: false
               })
           }
        })
    }
    handlePageChange = (page, pageSize) => {
        this.setState({
            currentPage: page,
            pageSize: pageSize
        }, () => {
            this.getDataList()
        })
    }
    handleSizeChange = (current, size) => {
        this.setState({
            currentPage: current,
            pageSize: size
        }, () => {
            this.getDataList()
        })
    }
    resetForm = () => {
        this.setState({
            currentPage: 1,
            pageSize: 10,
            dataForm:{}
        }, () => {
            this.getDataList()
        })
    }
    setVisible = () => {
        this.setState({
            visible: !this.state.visible,
        });
    };
    handleAddOrUpdate = (id) => {
        if(id){
            this.updateId = id
        }
        this.setVisible()
    }
    handleDelete = (id) => {
        reqDeleteDict([id]).then(({data}) => {
            if (data.code === 0) {
                message.success('删除成功')
            }
        })
    }
    handleOk = e => {
        this.setVisible()
        let valueData = this.form.getFieldsValue()
        if (this.updateId) {
            valueData = Object.assign(valueData, {id: this.updateId})
            reqUpdateDict(valueData).then(({data}) => {
                if (data.code === 0) {
                    message.success('编辑成功')
                    this.getDataList()
                }
            })
        } else {
            reqAddDict(valueData).then(({data}) => {
                if(data.code === 0){
                    message.success(data.msg)
                    this.getDataList()
                }
            })
        }
    };

    handleCancel = e => {
        this.form.resetFields()
        this.setVisible()
    };

    componentWillMount() {
        this.initColumns()
    }
    componentDidMount() {
        this.getDataList()
    }

    render(){
        const {dataList, listLoading, totalCount, currentPage, pageSize, dataForm } = this.state;
        const rowSelection = {
            onChange: (selectedRowKeys, selectedRows) => {
                console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
            },
            onSelect: (record, selected, selectedRows) => {
                console.log(record, selected, selectedRows);
            },
            onSelectAll: (selected, selectedRows, changeRows) => {
                console.log(selected, selectedRows, changeRows);
            },
        };
        return(
            <div>
                <Form layout="inline" className="search-wrap">
                    <Form.Item>
                        <Input placeholder="类型"
                               value={dataForm.type}
                               onChange={e => this.setState({dataForm: Object.assign(dataForm, {type: e.target.value})})}
                        />
                    </Form.Item>
                    <Form.Item>
                        <Input placeholder="类型名称"
                               value={dataForm.typeName}
                               onChange={e => this.setState({dataForm: Object.assign(dataForm, {typeName: e.target.value})})}
                        />
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit" icon="search" onClick={this.getDataList}>查询</Button>
                    </Form.Item>
                    <Form.Item>
                        <Button type="dashed" htmlType="submit" icon="redo" onClick={this.resetForm}>重置</Button>
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit" icon="plus" onClick={() => this.handleAddOrUpdate()}>新增</Button>
                    </Form.Item>
                    <Form.Item>
                        <Button type="danger" htmlType="submit" icon="delete">批量删除</Button>
                    </Form.Item>
                </Form>
                <Table
                    columns={this.columns}
                    rowKey={record => record._id}
                    rowSelection={rowSelection}
                    dataSource={dataList}
                    loading={listLoading}
                    bordered
                    pagination={
                        {
                            total: totalCount,
                            current: currentPage,
                            pageSize: pageSize,
                            showSizeChanger: true,
                            onChange:this.handlePageChange,
                            onShowSizeChange:this.handleSizeChange,
                            showTotal: (total) =>  `共${total}条`
                        }
                    }>
                </Table>
                {
                    this.state.visible && <Modal
                        title="新增"
                        visible={this.state.visible}
                        okText="确定"
                        cancelText="取消"
                        width="45%"
                        onOk={this.handleOk}
                        onCancel={this.handleCancel}
                    >
                        <AddOrUpdate
                            dataId = {this.updateId}
                            setForm = {(form) => this.form = form} />
                    </Modal>
                }
            </div>
        )
    }
}

function mapState(store) {
    return{
        dict: store.dict.dataList
    }
}
export default connect(mapState,{ getDataList })(Dict);